<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .weui-loadmore_line .weui-loadmore__tips {
    background-color: #eee;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  .weui-cells__title {
    text-align: left;
  }
  .oitem {
    padding: 3px;
  }
  .hide {
    display: none;
  }
  #acts {
    font-size: 0;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label {
    text-align: left;
  }

  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }
  .weui_uploader_hd {
    padding-top: 0;
    padding-right: 0;
    padding-left: 0;
  }
  .weui_uploader_files {
    list-style: none;
  }
  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }
  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }
  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }
  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }
  .weui_uploader_bd {
    overflow: hidden;
  }
  .weui_cell {
    padding: 10px 15px;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
  }
  .outstore >>> .weui-uploader_files {
    list-style: none;
    overflow-y: hidden;
  }
  .outstore >>> .weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }
  .weui-cell.fir {
    border-top: 0;
  }
  .help {
    text-align: right;
    padding: 5px;
    font-size: 12px;
    color: #bbb;
  }
</style>
<template>
  <div class="outstore">
    <div  id="aaa" style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      销售出库
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="../../assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="/api/sellform/add" method="post" id="formid">
        <div class="weui-cell weui-cell_select" style="padding: 0 15px;">
          <div class="weui-cell__hd"><label for="" class="weui-label">所属公司</label></div>
          <div class="weui-cell__bd">
            <select class="weui-select" name="entity.orgguid" v-model="orgguid" ref="orgguid">
              <option value="0" style="color: #ccc;">请选择所属公司</option>
              <option  v-for="(org, i) in orgs" :key="org.guid" :value="org.guid" >{{org.name}}</option>
            </select>
          </div>
        </div>
        <div class="weui-cell">
          <div class="weui-cell__hd"><label for="" class="weui-label">出库类型</label></div>
          <div class="weui-cell__bd">
            <select class="weui-select" name="" v-model="picktype">
              <option v-if="picktype == 1" value="1" >原材料库</option>
              <option v-if="picktype == 2 || picktype == 3" value="2" >产成品库</option>
              <option v-if="picktype == 2 || picktype == 3" value="3" >次品库</option>
            </select>
<!--            <input class="weui-input" type="text" name="" readonly="true" :value="sellform.quitSRType == 1 ? '原材料库' : '产成品库'">-->
          </div>
        </div>
        <div class="oitem" v-for="(product, index) in sellform.items" :key="product.guid">
          <input type="hidden" :name="'items[' + index + '].productguid'" :value="product.productguid" />
          <input type="hidden" :name="'items[' + index + '].productname'" :value="product.productname" />
          <input type="hidden" :name="'items[' + index + '].spguid'" :value="product.spguid" />
          <input type="hidden" :name="'items[' + index + '].price'" :value="product.price" />
          <div class="weui-cells__title">货品明细 {{index + 1}}
            <p id="acts" style="float: right;color: #1aad19;">
              <span @click="copyItem(index)" style="padding-right: 5px;">新增</span><span v-if="sellform.items.length > 1">|</span><span @click="delItem(index)" style="padding-left: 5px;" v-if="sellform.items.length > 1">删除</span>
            </p>
          </div>
          <div class="weui-cell fir">
            <div class="weui-cell__hd"><label class="weui-label">库房</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select room" :name="'items[' + index + '].shrguid'" :disabled="!canEditRoom">
                <option :value="sellform.storermguid">{{sellform.storeroomname}}</option>
                <option v-for="(item, i) in rooms" :key="item.guid" :value="item.guid">{{item.name}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">产品</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="" readonly="true" :value="product.productname">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">规格</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="" readonly="true" :value="product.spname">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label for="" class="weui-label">库间</label></div>
            <div class="weui-cell__bd">
              <!--              <input class="weui-input shrguid" :id="'shrguid' + index" type="text" name="" placeholder="请选择库间">-->
              <!--              <input type="hidden" :id="'shrid' + index" name="items[0].shrguid">-->
              <select class="weui-select room" :name="'items[' + index + '].shrguid'" >
                <option value="0">请选择库间</option>
                <option v-for="(hou, i) in autoHouses(index)" :key="hou.storeroomguid" :value="hou.storeroomguid">{{hou.storeroomName}} &nbsp; ({{hou.storeqty}} {{hou.unit}})</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">重量(吨)</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input weight" type="number" :name="'items[' + index + '].weight'" placeholder="请输入重量">
            </div>
          </div>
        </div>
        <p v-show="conditionSR" class="help" @click="expendPerm">跨库房出库？</p>
        <div class="weui-cells weui-cells_form">
          <div class="weui-cell">
            <div class="weui-cell__bd">
              <textarea class="weui-textarea" id="remark" name="entity.remark" placeholder="请输备注内容" rows="2"></textarea>
            </div>
          </div>
        </div>
        <div class="weui_cell">
          <div class="weui_cell_bd weui_cell_primary">
            <div class="weui_uploader">
              <div class="weui_uploader_hd weui_cell" style="padding-left: 0;">
                <div class="weui_cell_bd weui_cell_primary" @click="test">过磅单上传</div>
                <div class="weui_cell_ft" id="cell_nums"></div>
              </div>
              <div class="weui_uploader_bd">
                <ul class="weui_uploader_files" id="images2">
                  <li class="weui-uploader_file" v-for="(img, index) in images2.serverId" :id="img"  @click=del(img,2) ><img :src="images2.srcStr[index]" width="85" /></li>
                </ul>
                <div class="weui_uploader_input_wrp">
                  <input type="button" id="selectImage2"  class="weui_uploader_input" >
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="weui_cell">
          <div class="weui_cell_bd weui_cell_primary">
            <div class="weui_uploader">
              <div class="weui_uploader_hd weui_cell" style="padding-left: 0;">
                <div class="weui_cell_bd weui_cell_primary" id="outstore">出库单上传</div>
                <div class="weui_cell_ft" id=""></div>
              </div>
              <div class="weui_uploader_bd">
                <ul class="weui-uploader_files" id="images">
                  <li class="weui-uploader_file" v-for="(img, index) in images1.serverId" :id="img"  @click=del(img,1) ><img :src="images1.srcStr[index]" width="85" /></li>
                </ul>
                <div class="weui_uploader_input_wrp">
                  <input type="button" id="selectImage"  class="weui_uploader_input" >
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="weui-btn-area">
          <a class="weui-btn weui-btn_primary subbtn" href="javascript:" @click="postForm">出库</a>
        </div>
      </form>
    </div>
    <OperationLogs2 :orderid="id" :srguid="sellform.storermguid" :departid="sellform.depguid"></OperationLogs2>

  </div>
</template>

<script>
  import wx from 'weixin-js-sdk';
  import OperationLogs2 from '../common/OperationLogs2'

export default {
  name: 'OutStoreRoom',
  data () {
    return {
      openid: localStorage.openid,
      id: '',
      nodeid: '',
      annex: '',
      sellform: {},
      orgs: [],
      rooms: [],
      strmid: '',
      houses: [],
        dict:[],
      wxParams: {},
      status: '',
      quitSRType: '',
      orgguid: 0,
      orgname: '',
      canEditRoom: false,
      conditionSR: false,
      picktype: 2,
      images1: {
        serverId: [],
        srcStr: [],
      },
      images2: {
        serverId: [],
        srcStr: [],
        weight: []
      }
    }
  },
  components: {
    OperationLogs2
  },
  mounted () {
    let that = this;
    this.id = this.$route.query.guid;
    this.nodeid = this.$route.query.nodeid;
    this.annex = this.$route.query.annex;
    this.getOrder(this.id, this);
    this.getOrg();
    this.conditionSR = this.$route.query.conditionSR == 'true';
    if (this.$route.query.status) {
      this.status = this.$route.query.status;
    }
    $('.room').change(function () {
      let index = $(this).index();
      that.getPLInfo(index, that.orgguid, that.sellform.items[index].productguid, this.sellform.items[index].spguid);
    })
  },
  watch: {
    'orgguid': function (val) {
      let myselect = this.$refs.orgguid;
      let index=myselect.selectedIndex ;
      this.orgname = myselect.options[index].text;
      for(let i=0; i<this.sellform.items.length; i++) {
        this.getPLInfo(i, val, this.sellform.items[i].productguid, this.sellform.items[i].spguid);
      }
    },
    'picktype': function (val) {
      for(let i=0; i<this.sellform.items.length; i++) {
        this.getPLInfo(i, this.orgguid, this.sellform.items[i].productguid, this.sellform.items[i].spguid);
      }
    },

    // 'strmid': function (val) {
    //   let myselect = this.$refs.orgguid;
    //   let index=myselect.selectedIndex ;
    //   this.orgname = myselect.options[index].text;
    //   for(let i=0; i<this.sellform.items.length; i++) {
    //     this.getPLInfo(i, val, this.sellform.items[i].productguid, this.sellform.items[i].spguid);
    //   }
    // }
  },
  methods: {
    test: function() {
      this.images2.weight.push(12.3);
      this.setWeight();
    },
    autoHouses: function(no) {
      return this.houses['house' + no];
    },
    expendPerm: function() {
      this.canEditRoom = true;
    },
    copyItem: function(index) {
      this.sellform.items.splice(index, 0, this.sellform.items[index]);
      //更新新增items的库间
      this['house' + (index + 1)] = this['house' + index];
    },
    delItem: function(index) {
      this.sellform.items.splice(index, 1);
    },
    getRooms: function() {
      // this.axios({
      //   method: 'get',
      //   url: '/sales/Salespermission!getPermisForStore.action?openid=' + this.openid,
      //   params: {functionTypes: 1}
      // }).then(response => {
      //   if (response.data.msg == 'true') {
      //     this.rooms = response.data.storeroom.filter(this.removeCurrentRoom);
      //   } else if (response.data.msg == 'loginout') {
      //     this.toastError('请重新登录');
      //   } else {
      //     this.toastText('获取库房数据失败');
      //   }
      // });
      this.axios({
        method: 'get',
        url: '/sales/Whoutform!getSrByPermis.action',
        params: {openid: this.openid, funcType: 1}
      }).then(response => {
        if (response.data.srs != undefined) {
          this.rooms = response.data.srs.filter(this.removeCurrentRoom);
        } else if (response.data.status != false) {
          this.toastError(response.data.result);
        } else {
          this.toastSuccess('系统错误');
        }
      });
    },
    removeCurrentRoom: function(item) {
      return item.guid != this.sellform.storermguid;
    },
    wxConfig: function(wxParams) {
      wx.config({
        debug: false,            // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: wxParams.appid,    // 必填，公众号的唯一标识
        timestamp: wxParams.timestamp,  // 必填，生成签名的时间戳
        nonceStr: wxParams.nonceStr, // 必填，生成签名的随机串
        signature: wxParams.signature,// 必填，签名
        jsApiList: ['scanQRCode', 'chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表
      });
    },
    wxUoloadImage: function(that) {
      let cthis = this;
      //wx.ready(function(){
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        document.querySelector('#selectImage').onclick = function () {
          wx.chooseImage({
            success: function (res) {
              $(function(){
                $.each( res.localIds, function(i, n){
                  wx.uploadImage({
                    localId: n,
                    isShowProgressTips: 1,
                    success: function (res) {
                      if (that.checkCore() == 'ios') {
                        wx.getLocalImgData({
                          localId: n, // 图片的localID
                          success: function (res2) {
                            cthis.$nextTick(function () {
                              cthis.images1.srcStr.push(res2.localData);
                            })
                          }
                        });
                      } else {
                        cthis.$nextTick(function () {
                          cthis.images1.srcStr.push(n);
                        })
                      }

                      cthis.images1.serverId.push(res.serverId);
                    },
                    fail: function (res) {
                      $.alert(JSON.stringify(res));
                    }
                  });
                });
              });
            }
          });
        };
        document.querySelector('#selectImage2').onclick = function () {
          wx.chooseImage({
            success: function (res) {
              $(function(){
                $.each( res.localIds, function(i, n){
                  wx.uploadImage({
                    localId: n,
                    isShowProgressTips: 1,
                    success: function (res) {
                      if (that.checkCore() == 'ios') {
                        wx.getLocalImgData({
                          localId: n, // 图片的localID
                          success: function (res2) {
                            cthis.$nextTick(function () {
                              cthis.images2.srcStr.push(res2.localData);
                            })
                          }
                        });
                      } else {
                        cthis.$nextTick(function () {
                          cthis.images2.srcStr.push(n);
                        })
                      }
                      cthis.images2.serverId.push(res.serverId);
                      if (cthis.sellform.storermguid == '542414C110644DD9B7D0E881968B55AE') {
                        cthis.getWeightByImg(res.serverId);
                      }
                    },
                    fail: function (res) {
                      $.alert(JSON.stringify(res));
                    }
                  });
                });
              });
            }
          });
        };
      //});

    },
    getWeightByImg: function(imgid) {
      this.axios({
        method: 'post',
        url: '/system/IOCR!recognise.action',
        params: {imgid: imgid}
      }).then(response => {
        let data = response.data;
        if (data.code == 1) {
          for (let i=0; i<data.msg.length; i++) {
            if (data.msg[i].word_name == 'NetWeight') {
              this.images2.weight.push(data.msg[i].word);
              this.setWeight();
            }
          }
          //alert('重量： ' + JSON.stringify(response.data))
        }
      });
    },
    setWeight: function() {
      let items = this.sellform.items;
      if (items.length == 1 && $('.weight').eq(0).val() == '') {
        $('.weight').eq(0).val(this.images2.weight[0]);
      }
    },
    del: function (id, index){
      let cthis = this;
      $.actions({
        actions: [{
          text: "删除",
          onClick: function() {
            $.confirm("确定删除?", function() {
              //点击确认后的回调函数
              //删掉id
              var ids = cthis['images' + index].serverId;
              var a =  ids.indexOf(id);
              cthis.$nextTick(function () {
                cthis['images' + index].serverId.splice(a,1);
                cthis['images' + index].srcStr.splice(a,1);
              })
            }, function() {
              //点击取消后的回调函数
            });
          }
        }
        ]
      });
    },
    checkCore:function() {
      var u = navigator.userAgent;
      //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;//g
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);   //ios终端
      if (isIOS) {
        return 'ios';
      } else  {
        return 'android';
      }
    },
    getWxSignLink: function() {
      // 记录进入 App 时的 URL
      if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
        window.entryUrl = location.href;
      }

      return /(Android)/i.test(navigator.userAgent) ? location.href : window.entryUrl;
    },
    getOrg: function() {
      this.axios({
        method: 'get',
        url: '/sales/Whoutform!getOrg.action',
        params: {openid: this.openid}
      }).then(response => {
        if (response.data.orgs != undefined) {
          this.orgs = response.data.orgs;
          // if (response.data.orgs.length > 0) {
          //   this.orgguid = response.data.orgs[0].guid;
          // }
        }
      });
    },
    getPLInfo: function(index, orgguid, productid, spguid) {
      this.axios({
        method: 'get',
        url: '/sales/Whoutform!getPLInfo.action?openid=' + this.openid,
        params: {orgid: orgguid, strmid: this.sellform.storermguid, picktype: this.picktype, productid: productid, spec: spguid}
      }).then(response => {
        if (response.data.houses != undefined) {
          let houseitem = 'house' + index;
          this.$set(this.houses, houseitem, response.data.houses);
          //this[houseitem] = response.data.houses;
        }
      });
    },
    getOrder: function(id, that) {
      this.axios({
        method: 'post',
        url: '/sales/Whoutform!saleOutForm.action',
        params: {openid: this.openid, orderid: id, url: location.href.split("#")[0]}
      }).then(response => {
        if (response.status == 200) {
          this.sellform = response.data.saleform;

          this.getRooms();

          this.picktype = this.sellform.quitSRType;
          this.strmid = response.data.saleform.storermguid;
          this.dict = response.data.dict;



            let wxParams = response.data.params;
          //配置微信公众号参数
          this.wxConfig(response.data.params);
          //上传
          this.wxUoloadImage(that);
        } else {
          this.toastError('系统错误' + response.data.msg);
        }
      });
    },
    checkEmy: function(elem){
      let isFieldNotEmy = true;
      for (let i=0; i<$('.' + elem).length; i++) {
        if ($('.' + elem).eq(i).val() <= 0) {
          isFieldNotEmy = false;
          break;
        }
      }
      return isFieldNotEmy;
    },
    postForm: function () {
      if (!this.checkEmy('weight')) {
        this.toastText('重量有误！');
        return false;
      } else if (!this.checkEmy('room')) {
        this.toastText('库间有误！');
        return false;
      } else {
        if (this.annex.indexOf('whout') > -1) {
          if (this.images1.serverId.length == 0) {
            this.toastText('请上传出库单！');
            return false;
          }
        }
        if (this.annex.indexOf('weigh') > -1) {
          if (this.images2.serverId.length == 0) {
            this.toastText('请上传过磅单！');
            return false;
          }
        }
      }
      //防止重复提交
      $('.subbtn').attr("disabled",true).css("pointer-events","none");

      let postData = {};
      postData = this.serialize2Obj($("#formid").serializeArray());
      postData.whoutformIds = this.images1.serverId.join(',');
      postData.overweightIds = this.images2.serverId.join(',');
      postData.orderid = this.id;
      postData.nodeid = this.nodeid;
      //postData.status = this.status;
      postData.opttype = 2;
      postData['entity.orgname'] = this.orgname;
      this.axios({
        method: 'post',
        url: '/sales/Whoutform!doSaleOutForm.action?openid=' + this.openid,
        params: postData
      }).then(response => {
        //恢复提交按钮可点击
        $('.subbtn').attr('disabled', false).css("pointer-events","auto");

        if (response.data.msg == 'success') {
          this.toastSuccess('出库成功!');
          this.$router.push({name: 'Sellform', query:{stat: this.status}});
        } else if (response.data.msg == 'canotopt') {
          this.toastError('不允许的操作');
        } else {
          this.toastError('系统错误' + response.data.msg);
        }
      }).catch(function (error) {
        //恢复提交按钮可点击
        $('.subbtn').attr('disabled', false).css("pointer-events","auto");
        this.toastError('系统错误');
      });

    },
    // serialize2Obj: function (data) {
    //   var obj = {};
    //   $.each(data,function(i,v){
    //     obj[v.name] = v.value;
    //   })
    //   return obj;
    // }
  }
}
</script>
